package dao

import (
	"context"
	_ "embed"
	"github.com/olivere/elastic/v7"
	"golang.org/x/sync/errgroup"
	"time"
)

var (
	//go:embed article_index.json
	articleIndex string
	//go:embed user_index.json
	userIndex string
)

const (
	ArticleIndexName = "article_idx"
	UserIndexName    = "user_idx"
	TagIndexName     = "tag_idx"
	CollectIndexName = "collect_idx"
	LikeIndexName    = "like_idx"
)

func InitClient() *elastic.Client {
	client, err := elastic.NewClient(
		elastic.SetURL("http://192.168.71.144:9200"),
		elastic.SetSniff(false), // SetSniff启用或禁用嗅探器（默认情况下启用）
	)
	if err != nil {
		panic(err)
	}
	return client
}
func InitIndex(client *elastic.Client) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()
	var eg errgroup.Group
	eg.Go(func() error {
		return tryCreateIndex(ctx, client, UserIndexName, userIndex)
	})
	eg.Go(func() error {
		return tryCreateIndex(ctx, client, ArticleIndexName, articleIndex)
	})
	//eg.Go(func() error {
	//	return tryCreateIndex(ctx, client, TagIndexName, articleIndex)
	//})

	return eg.Wait()
}
func tryCreateIndex(ctx context.Context, client *elastic.Client, idxName, idxCfg string) error {
	ok, _ := client.IndexExists(idxName).Do(ctx)
	if ok {
		return nil
	}
	_, err := client.CreateIndex(idxName).BodyString(idxCfg).Do(ctx)
	return err
}
